const Koa = require('koa')
const router = require('koa-router')()
const render = require('koa-art-template')
const path = require('path')
const static = require('koa-static')
const session = require('koa-session')
const bodyParser = require('koa-bodyparser')
const mongoose = require('mongoose')
const app = new Koa()
//格式化日期的模块
const sd = require('silly-datetime')
const jsonp = require('koa-jsonp')

let index = require('./routes/index')
let api = require('./routes/api')
let admin = require('./routes/admin')
//配置post请求接受参数中间件
app.use(bodyParser())
app.use(jsonp())
//配置session中间件
app.keys = ['some secret hurr']

const CONFIG = {
  key: 'koa:sess',
  maxAge: 864000,
  overwrite: true,
  httpOnly: true,
  signed: true,
  rolling: true,
  renew: false
}

app.use(session(CONFIG, app))

//配置模板引擎
render(app, {
  root: path.join(__dirname, 'views'),
  extname: '.html',
  debug: process.env.NODE_ENV !== 'production',
  dateFormat: dateFormat = function (value) {
    return sd.format(value, 'YYYY-MM-DD HH:mm')
  }
})

//配置静态资源
app.use(static(__dirname + '/public'))

router.use('/', index)
router.use('/admin', admin)
router.use('/api', api)


app.use(router.routes())
app.use(router.allowedMethods())


//连接数据库并且启动服务
//mongoose.Promise = global.Promise
/*mongoose.connect('mongodb://blog:mm19900326@127.0.0.1/blog',{ useMongoClient: true }, function (err) {
    if (err) {
        console.log('数据库连接错误');
    } else {
        app.listen(80, function () {
            console.log('数据库连接成功，启动成功：端口为3000');
        });
    }
});*/
mongoose.connect('mongodb://localhost:27017/koa',{useNewUrlParser: true}).then(() => {
  app.listen(3000, function () {
    console.log('数据库连接成功, http://localhost:3000');
  })
})

